
import uuid
import datetime

from django.shortcuts import HttpResponse, render, redirect
from web.myform.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm
from django.conf import settings
from django.http import JsonResponse
from libs.tengxunyun.sms import MySmsSender
from django.urls import reverse
from web.utils.img_code import image_code
from web import models



from django.db.models import Q
import redis
from django_redis import get_redis_connection
#
# def login(request):
#
#     conn = get_redis_connection('sms_code') #default
#     conn.set('xx3', 'oo3')
#
#
#     return HttpResponse('ok')

# 注册功能
def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    # todo 校验注册数据
    else:
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():

            instance = form.save()  #instance就是当前记录对象
            # 注册成功之后，直接给用户一个免费版的策略
            price_policy_obj = models.PircePolicy.objects.filter(catogory=1,title='免费版').first()
            # 创建交易记录
            models.Transaction.objects.create(
                status=2,
                order=uuid.uuid4(),
                user=instance,
                price_policy=price_policy_obj,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now(),
            )

            return JsonResponse({'status': True, 'path': reverse('login_sms')})
        else:

            return JsonResponse({'status': False, 'error_msg': form.errors})


# 获取手机号，校验手机号，发送短信验证码
def sms_code(request):
    # 18201734941, 18201734941
    # 校验手机号格式，手机号唯一性验证
    # request.GET.get('phone')

    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():

        # print(reverse('login'))
        return JsonResponse({'status': True })

    else:
        return JsonResponse({'status': False, 'error_msg': form.errors})


# 短信验证码登录
def login_sms(request):
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})

    else:
        form = LoginSmsForm(data=request.POST)
        if form.is_valid():
            phone = form.cleaned_data.get('phone')

            user_obj = models.UserInfo.objects.filter(phone=phone).first()
            # 可以先清空session，或者给session设置个新的有效期
            # request.session.flush()
            # 将登录成功之后的数据保存到session，便后续使用
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)

            return JsonResponse({'status': True, 'path': reverse('index')})


        else:
            return JsonResponse({'status': False, 'error_msg': form.errors})


def login(request):
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html',{'form': form})

    else:
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            # todo 将登录成功之后的数据保存到session，便后续使用
            uname = form.cleaned_data.get('username')

            user_obj = models.UserInfo.objects.filter(Q(phone=uname)| Q(email=uname)).first()

            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)

            return JsonResponse({'status': True, 'path': reverse('index')})

        else:
            return JsonResponse({'status': False, 'error_msg': form.errors})


def img_code(request):
    img, char_code = image_code()
    # 将图片数据写到内存
    from io import BytesIO
    stream = BytesIO()
    img.save(stream, format='png')
    # 内存中获取图片数据getvalue()，结果为bytes数据


    # 将图片数据保存到本地文件中
    # with open('code.png', 'wb') as f:
    #     # save保存图片
    #     img.save(f, format='png')
    #
    # with open('code.png', 'rb') as f:
    #     # save保存图片
    #     data = f.read()

    # 将图片验证码保存到session中
    request.session['image_code'] = char_code
    # 图片验证码有效期,单位秒
    request.session.set_expiry(settings.IMAGE_CODE_EXPIRE)

    return HttpResponse(stream.getvalue())
    # return HttpResponse(data)


def logout(request):
    request.session.flush()
    return redirect('login')

def index(request):

    return render(request, 'index.html')




